import { Tree } from 'antd';
import React, { FC, useEffect, useState } from 'react';
import { request } from 'umi';
interface TreeProps {
    value?: string,
    onChange?: (value: string) => void
}
const SelectUnitTree: FC<TreeProps> = (props: TreeProps) => {
    const {
        value,
        onChange
    } = props;
    const [treeData, settreedata] = useState([]);
    const getdata = () => {
        request('/data/dynamic/query', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            data: {
                apiID: 'GL_001'
            }
        }).then((res) => {
            let data = res?.data?.data;
            let obj = {};
            data.sort((a, b) => {
                return a.org_level - b.org_level;
            });
            data.forEach((item) => {
                if (item?.up_org_code == '') {
                    obj[item?.org_code] = item;
                }
            });
            data.forEach((item) => {
                if (item?.up_org_code) {
                    obj = handleObj(obj, item);
                }
            });
            console.log(obj);
            let arr = handleData(obj);
            settreedata(arr);
        });
    };
    const handleObj = (obj, item) => {
        if (obj[item?.up_org_code]) {
            if (!obj[item?.up_org_code]['children']) {
                obj[item?.up_org_code]['children'] = {};
            }

            obj[item?.up_org_code]['children'][item?.org_code] = item;
        } else {
            for (let i in obj) {
                if (obj[i]['children']) {
                    obj[i]['children'] = handleObj(obj[i]['children'], item);
                }
            }
        }

        return obj;
    };
    const handleData = (obj) => {
        let arr = [];
        for (let i in obj) {
            let item = {
                title: obj[i]['org_name'],
                key: obj[i]['org_code_id'] + ''
            };
            if (obj[i]['children']) {
                item['children'] = handleData(obj[i]['children']);
            }

            arr.push(item);
        }
        return arr;
    };
    useEffect(() => {
        getdata();
    }, []);
    return <div >
        {
            treeData.length > 0 && <Tree
                treeData={treeData}
                defaultCheckedKeys={[value]}
                selectedKeys={[value]}
                defaultExpandAll
                onSelect={(selectedKeys, e) => {
                    props.onChange && props.onChange(selectedKeys[0], e);
                }}
            />
        }
    </div >
}


export default SelectUnitTree;